package com.fly.visit;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import com.fly.core.util.JsonBeanUtils;
import com.fly.visit.entity.Article;
import com.fly.visit.entity.BlogData;
import com.fly.visit.service.TokenService;
import com.fly.visit.service.WebVisitorSevice;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@ConditionalOnWebApplication
public class IndexController
{
    @Autowired
    HttpSession httpSession;
    
    @Autowired
    TokenService tokenService;
    
    @Autowired
    WebVisitorSevice webVisitorSevice;
    
    /**
     * 首页index.html使用thymeleaf，登录成功情况下，多行文本框可提交数据初始化articles
     * 
     * @param model
     * @return
     */
    @GetMapping({"/", "/index"})
    public String index(Model model)
    {
        String token = (String)httpSession.getAttribute("token");
        if (tokenService.valide(token))
        {
            model.addAttribute("isLogin", true);
            model.addAttribute("sysTokenTime", tokenService.getTokenTime());
        }
        return "index";
    }
    
    @PostMapping("/login")
    public String login(String token)
    {
        if (tokenService.valide(token))
        {
            httpSession.setAttribute("token", token);
        }
        return "redirect:/index";
    }
    
    /**
     * 提交URL数据
     * 
     * @param data
     * @return
     * @throws IOException
     */
    @PostMapping("/urls/submit")
    public String urlsSubmit(String data)
        throws IOException
    {
        String token = (String)httpSession.getAttribute("token");
        if (tokenService.valide(token))
        {
            List<Article> list = JsonBeanUtils.jsonToBean(data, BlogData.class, true).getData().getList();
            if (!list.isEmpty())
            {
                webVisitorSevice.setArticles(list);
            }
        }
        else
        {
            log.error("token非法，请先登录");
        }
        return "redirect:/index";
    }
    
    @GetMapping("/logout")
    public String logout()
    {
        httpSession.invalidate();
        return "redirect:/index";
    }
}
